"""Re-parse saved LLM raw responses for assessments marked as failed/parse_error.

Run this script from the backend root with the project's Python environment.
It will look for assessments where ai_response->parse_error == true, try to re-parse
using the same parser, and update the assessment record if parsing succeeds.
"""
import asyncio
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy import select, update
from sqlalchemy.orm import sessionmaker
import os

# Minimal imports from the app
from app.core.ai_evaluator import AIEvaluator
from app.db.session import settings as db_settings
from app.models.assessment import Assessment

DATABASE_URL = os.getenv('DATABASE_URL', db_settings.DATABASE_URL)

async def main():
    engine = create_async_engine(DATABASE_URL, echo=False)
    async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

    async with async_session() as session:
        stmt = select(Assessment).where(Assessment.ai_response['parse_error'].astext == 'true')
        result = await session.execute(stmt)
        items = result.scalars().all()
        print(f"Found {len(items)} assessments with parse_error=true")

        evaluator = AIEvaluator()

        for a in items:
            raw = a.ai_response.get('raw') if a.ai_response else None
            if not raw:
                continue
            print(f"Reparsing assessment {a.id} for record {a.record_id}")
            parsed = evaluator._parse_llm_response_enhanced(raw)
            if parsed and not parsed.get('parse_error'):
                # Update assessment entry
                a.overall_score = parsed['overall_score']
                a.completeness_score = parsed['completeness_score']
                a.standardization_score = parsed['standardization_score']
                a.consistency_score = parsed['consistency_score']
                a.accuracy_score = parsed['accuracy_score']
                a.summary = parsed.get('summary')
                a.suggestions = parsed.get('suggestions')
                a.status = 'completed'
                await session.commit()
                print(f"Updated assessment {a.id} with re-parsed results")
            else:
                print(f"Reparse failed for {a.id}")

if __name__ == '__main__':
    asyncio.run(main())
